import ast
import os


stu_list = []
student_file = 'student.txt'

# 录入学生信息
def insert_info():
    load_info()
    global stu_list
    print('录入学生信息')
    flag = True
    while flag:
        stu_id = input('请输入学号：')
        for stu in stu_list:
            if stu['student_number'] == stu_id:
                print("您输入的学号已经存在，请重新输入：")
                return  # 直接从函数返回，也就退出了while循环
            else:
                continue
        name = input('请输入姓名：')
        if stu_id.strip() == '' or name.strip() == '':
            # 删除前后空格
            print('学号和姓名均不能为空')
            continue
        try:
            grade1 = float(input('请输入python成绩:'))
            grade2 = float(input('请输入数据分析成绩:'))
        except ValueError:
            print('成绩请输入数字')
            continue
        student_info = {'student_number': stu_id, 'name': name, 'python_score': grade1, 'date_score': grade2}
        # global stu_list
        stu_list.append(student_info)
        # 存列表
        print(student_info)
        more = input('是否继续输入：（y/n）')
        if more != 'y':
            save_info(stu_list)
            print('所有学生信息已保存')
            flag = False

# 查询学生信息
def search_info():
    print('查找学生信息')
    load_info()
    result = []
    method = (input('1-通过学号查询 2-通过姓名查询:'))
    if method == '1':
        query = input('请输入要查询的学号：')
        for stu in stu_list:
            if stu['student_number'] == query:
                result.append(stu)
    elif method =='2':
        query =input('请输入要查询的名字:')
        for stu in stu_list:
            if stu['name'] ==query:
                result.append(stu)
    else:
        print('输入错误')
        return
    show_info(result)

#删除学生信息
def delete_info():
    load_info()
    if not stu_list:
        print("没有学生信息！")
        return
    else:
        show_info(stu_list)
        stu_id=input("请输入要删除的学生学号：")
        for stu in stu_list:
            if stu['student_number'] == stu_id:
                stu_list.remove(stu)
                save_info(stu_list)
                print("已删除学生信息")
                return

# 修改学生信息
def revise_info():
    print("修改学生信息")
    stu_list = load_info()
    if not stu_list:
        print("没有学生信息！")
        return
    else:
        show_info(stu_list)
        stu_id=input("请输入要修改学生的学号：")
    flag = True
    while flag:
        found = False
        for stu in stu_list:
            if stu['student_number'] == stu_id:
                found = True
                print('提示：可输入:name，python_score，date_score，all')
                revise =input('请输入您要修改的部分，all表示全部修改：')
                if revise=='name':
                    name1=input('请输入修改后的名字:')
                    if name1.strip() == '':
                        print('姓名不能为空')
                        continue
                    else:
                        stu['name'] = name1
                        save_info(stu_list)
                        print("已修改学生信息")
                        return
                elif revise=='python_score':
                    try:
                        stu['python_score'] = float(input('请输入修改后的python_score:'))
                    except ValueError:
                         print('成绩请输入整数')
                         continue
                    save_info(stu_list)
                    print("已修改学生信息")
                    return
                elif revise=='date_score':
                    stu['date_score']=float(input('请输入修改后的date_score:'))
                    try:
                        stu['python_score'] = float(input('请输入修改后的python_score:'))
                    except ValueError:
                         print('成绩请输入整数')
                         continue
                    save_info(stu_list)
                    print("已修改学生信息")
                    return
                elif revise=='all':
                    stu_list.remove(stu)
                    save_info(stu_list)
                    stu_id = input('请输入学号：')
                    name = input('请输入姓名：')
                    if stu_id.strip() == '' or name.strip() == '':
                        # 删除前后空格
                        print('学号和姓名均不能为空')
                    try:
                        grade1 = float(input('请输入python成绩:'))
                        grade2 = float(input('请输入数据分析成绩:'))
                    except ValueError:
                        print('成绩请输入整数')
                        continue
                    student_info = {'student_number': stu_id, 'name': name, 'python_score': grade1,
                                    'date_score': grade2}
                    stu_list.append(student_info)
                    print(student_info)
                    save_info(stu_list)
                    print('所有修改信息已保存')
                    flag = False
        if not found:
            print('您输入的学号不存在')
            flag = False

# 学生信息排序
def sort_info():
    print('学生信息排序')
    choose = int(input('排序方式0-升序；1-降序；请输入：'))
    choose2 = input('排序依据0-python成绩；1-数据分析成绩；2-总成绩；请输入：')
    if choose == 0:
        stu_list = load_info()
        if not stu_list:
            print("没有学生信息！")
            return
        else:
            if choose2 == '0':
                stu_list.sort(key=lambda student: student['python_score'])
                show_info(stu_list)
                print("已按照python成绩升序排列")
                statistic_info()
                return
            elif choose2 == '1':
                stu_list.sort(key=lambda student: student['date_score'])
                show_info(stu_list)
                print('已按照date成绩升序排列')
                statistic_info()
                return
            elif choose2 == '2':
                stu_list.sort(key=lambda student: student['python_score'] + student['date_score'])
                show_info(stu_list)
                print("已按照总成绩升序排列")
                statistic_info()
                return
    if choose == 1:
        stu_list = load_info()
        if not stu_list:
            print("没有学生信息！")
            return
        else:
            if choose2 == '0':
                stu_list.sort(key=lambda student: student['python_score'], reverse=True)
                show_info(stu_list)
                print("已按照python成绩降序排列")
                statistic_info()
                return
            elif choose2 == '1':
                stu_list.sort(key=lambda student: student['date_score'], reverse=True)
                show_info(stu_list)
                print('已按照data成绩降序排列')
                statistic_info()
                return
            elif choose2 == '2':
                stu_list.sort(key=lambda student: student['python_score'] + student['date_score'], reverse=True)
                show_info(stu_list)
                print("已按照总成绩降序排列")
                statistic_info()
                return

# #将信息传入student.txt
def save_info(stu_list):
    with open('student.txt','w',encoding='utf-8')as file:#打开
        for stu in stu_list:
            file.write(str(stu)+'\n')

#读出student.txt的信息
def load_info():
    global stu_list
    stu_list = []
    if os.path.exists(student_file):
        with open(student_file, 'r', encoding='utf-8') as file:
            for line in file:
                try:
                    stu = ast.literal_eval(line)  # 使用 ast.literal_eval 安全地解析字符串为字典
                    stu_list.append(stu)
                except (SyntaxError, ValueError):
                    print(f"无法解析行: {line.strip()}")
    return stu_list

#规范输出查询信息
def show_info(result):
    print(f"一共有{len(result)}名学生")
    print('{:<10}{:<10}{:<10}{:<10}'.format('学号', '姓名', 'python成绩', '数据分析成绩'))
    for res in result:
        print('{:<12}{:<12}{:<12}{:<10}'.format(res['student_number'], res['name'], res['python_score'],
                                                res['date_score']))

#输出最高分，最低分，平均分，合格率
def statistic_info():
    load_info()
    x=0
    y=10000
    z=0
    h=10000
    a=0
    b=0
    c=0
    d=0
    for stu in stu_list:
        if stu['python_score']>x:
            x=stu['python_score']
        if  stu['python_score']<y:
            y=stu['python_score']
        if stu['date_score']>z:
            z=stu['date_score']
        if  stu['date_score']<h:
            h=stu['date_score']
        a+=stu['python_score']
        b+=stu['date_score']
        if stu['python_score']>60.0:
            c+=1
        if stu['date_score']>60.0:
            d+=1
    print(
        f'python最高分为：{x},python的最低分为：{y},python的平均分为{a / len(stu_list):.2f},python的合格率为{c / len(stu_list):.2f}')
    print(
        f'数据分析最高分为{z},数据分析的最低分为{h},数据分析的平均分为{b / len(stu_list):.2f},据分析的合格率为{d / len(stu_list):.2f}')




if __name__ == '__main__':#直接执行时才执行以下代码，被导入时不执行
    while True:
        print('''
                   ——————————————————————学生管理系统——————————————————
                   |                                                |
                   |   ===============系统功能名单==================== |
                   |   1 录入学生信息                                  |
                   |   2 查找学生信息                                  |
                   |   3 删除学生信息                                  |
                   |   4 修改学生信息                                  |
                   |   5 学生信息排序                                  |
                   |   0 退出学生管理系统                               |
                   |    ======================================       |
                   |    说明：通过数字或⬆⬇方向键选择菜单                    |
                    —————————————————————————————————————————————————
                    ''')
        option = input('请输入要操作的编号：')
        if option == '1':
            insert_info()
        elif option == '2':
            search_info()
        elif option == '3':
            delete_info()
        elif option == '4':
            revise_info()
        elif option == '5':
            sort_info()
        elif option == '0':
            print('退出学生管理系统')
            break




